
//Copyright 1997-2009 Syrinx Development, Inc.
//This file is part of the Syrinx Web Application Framework (SWAF).
// == BEGIN LICENSE ==
//
// Licensed under the terms of any of the following licenses at your
// choice:
//
//  - GNU General Public License Version 3 or later (the "GPL")
//    http://www.gnu.org/licenses/gpl.html
//
//  - GNU Lesser General Public License Version 3 or later (the "LGPL")
//    http://www.gnu.org/licenses/lgpl.html
//
//  - Mozilla Public License Version 1.1 or later (the "MPL")
//    http://www.mozilla.org/MPL/MPL-1.1.html
//
// == END LICENSE ==
using System;
using System.IO;

namespace Swaf.Messaging
{
	/// <summary>
	/// Summary description for SmtpHelper.
	/// </summary>
	public class SmtpHelper
	{
		/// <summary>
		/// Default constructor.
		/// </summary>
		public SmtpHelper() {}

		/// <summary>
		/// This routines sends the message using the SMTP transport
		/// The Relay restrictions on the Access tab of the virtual SMTP service
		/// must be modified to "All except the list below" in order for messages 
		/// to be sent successfully.  
		/// </summary>
		public Boolean SendSmtpMessage(EmailMessage emsg)
		{
			try
			{
				// Init the message
				System.Web.Mail.MailMessage msg = new System.Web.Mail.MailMessage();
				
				// TODO: HANDLE MULTIPLE ATTACHMENTS
				// Process the attachments
                foreach (EmailAttachment a in emsg.Attachments)
                {
                    if (a.Path != null || a.Path.Trim().Length != 0)
                    {
                        System.Web.Mail.MailAttachment attachment = new System.Web.Mail.MailAttachment(Path.Combine(a.Path, a.Name));
                        msg.Attachments.Add(attachment);
                    }
                }
				
				// Populate message properties
				msg.To = emsg.To;
				msg.From = emsg.From;
				msg.Cc = emsg.Cc;
				msg.Bcc = emsg.Bcc;
				msg.Subject = emsg.Subject;
				msg.Priority = (System.Web.Mail.MailPriority)Enum.Parse(typeof(System.Web.Mail.MailPriority), emsg.Priority, true);
				msg.BodyFormat = (System.Web.Mail.MailFormat)Enum.Parse(typeof(System.Web.Mail.MailFormat), emsg.Format, true);
				msg.Body = emsg.Body;
				
				// Set the smtp server to be used and send the message
				System.Web.Mail.SmtpMail.SmtpServer = emsg.HostName;
				System.Web.Mail.SmtpMail.Send(msg);
			}
			catch (Exception e)
			{ 
				// TODO DO HANDLE EXCEPTION
				e = e.GetBaseException();
				throw e;
			}

			return true;
		}
	}
}
